<?php
namespace control;
// 安装调试
class installDebugClass extends adIndexClass
{
    private const page = 'installDebug'; # 权限
    private const table = 'install_debug'; # 数据表
    private const tableInstall = 'install_record';//安装记录表
    private const tableDebug = 'debug_record'; # 调试记录表
    private const title = '安装调试';
    private const stateOption = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName' => [
                        'name'  => "客户名称",
                        'width' => 150,
                    ],
                    'equipmentName'  => [
                        'name'  => "设备名称",
                        'width' => 200,
                    ],
                    'equipmentCode'  => [
                        'name'  => "设备编码",
                        'width' => 150,
                    ],
                    'instaff_director'  => [
                        'name'  => "安装责任人",
                        'width' => 150,
                    ],
                    'install_result'         => [
                        'name'  => '安装结果',
                        'width' => 100,
                    ],
                    'debug_conclusion'          => [
                        'name'  => '调试结论',
                        'width' => 200,
                    ],
                    'install_time'          => [
                        'name'  => '安装时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "客户名称"   => text(array("name" => "clientName")),
                    "设备名称"   => text(array("name" => "equipmentName")),
                ],
                [
                    "设备编码"   => text(array("name" => "equipmentCode")),
                    '安装负责人'  => selectMultiple(['table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'instaff_director', 'where' => " state <> '离职' "]),
                    "安装结果"   => text(array("name" => "install_result")),
                ],
                [
                    "调试结论"   => text(array("name" => "debug_conclusion")),
                    "安装时间" => text(array("name" => "install_time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*委外合同入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=editPage')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= spanButton(['name' => '删除', 'page' => self::page, 'fun' => 'operate', 'para' => ['act' => 'del'], 'first' => true]);
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*委外合同列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'instaff_director' => $this->post('instaff_director'),
            'state' => $this->post('state'),
            'coid'=>self::$coid
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
            'install_result' => $this->post('install_result'),
            'debug_conclusion' => $this->post('debug_conclusion'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('install_time')) {
            $where .= self::timeComparison($this->post('install_time'), 'date', 'install_time');
        }
        if($this->post('clientName')){
            $where .= " and client_id in (select khid from kehu where companyName like '%".$this->post('clientName')."%' and coid = '".self::$coid."') ";
        }
        if($this->post('equipmentName') || $this->post('equipmentCode')){
            $and = '';
            if($this->post('equipmentName')){
                $and .= " and name like '%".$this->post('equipmentName')."%' ";
            }
            if($this->post('equipmentCode')){
                $and .= " and code like '%".$this->post('equipmentCode')."%' ";
            }
            $where .= " and equipment_id in (select id from equipment where coid = '".self::$coid."' {$and}) ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => "安装调试详情", "click" => "newIframe('安装调试详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
                "edit" => $array['state'] == '草稿' ? ["title" => "安装调试编辑", "click" => "newIframe('安装调试编辑','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $array['id'] . "')"] : [],
            ];
            $equipment = query('equipment', "id = '$array[equipment_id]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu = query('kehu', "khid = '$array[client_id]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case 'equipmentName':
                        $row[] = $equipment['name'];
                        break;
                    case 'equipmentCode':
                        $row[] = $equipment['code'];
                        break;
                    case 'instaff_director':
                        $row[] = self::findStaff($array['instaff_director']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editPageEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    public function editPage()
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        // 安装记录
        $installTr[] = ['', '作业项', '操作目的', '注意事项', '操作结果'];
        $type = 'install';
        $result = find(['table' => self::tableInstall, 'where' => "orderId = '{$info['id']}' order by list asc"]);
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array = (new salesContractClass())->prefixArrayKeys($array,$type);
                $array['list'] = $k+1;
                $installTr[] = $this->installRow($array);
            }
        }else{
            $installTr[] = $this->installRow([$type.'id'=>self::getId(), 'list'=>1]);
        }
        // 调试记录
        $debugTr[] = ['', '调试轮次', '关键参数', '注意事项', '调试结论'];
        $type = 'debug';
        $result = find(['table' => self::tableDebug, 'where' => "orderId = '{$info['id']}' order by list asc"]);
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array = (new salesContractClass())->prefixArrayKeys($array,$type);
                $array['list'] = $k+1;
                $debugTr[] = $this->debugRow($array);
            }
        }else{
            $debugTr[] = $this->debugRow([$type.'id'=>self::getId(), 'list'=>1]);
        }
        //按钮
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "EditPageForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            "post" => ["id" => $this->get('id')],
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        //审核按钮
        $equipment = query("equipment"," id = '$info[equipment_id]' ");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '客户名称' => selectMultiple(['table' => 'kehu', "title" => '请选择', 'sqlField' => 'companyName', 'sqlId' => 'khid', 'name' => 'client_id', 'where' => "coid = '" . self::$coid . "'", 'value' => $info['client_id']]),
                    must . '设备' => hidden(['name' => 'equipment_id', 'value' => $info['equipment_id']]) . '<span id="equipmentName">' . ($info['equipment_id'] ? $equipment['name'] : '未选择') . '</span>' . "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addEquipment',{})\" style='margin-left: 10px'>选择</span>",
                    must . '安装责任人' => selectMultiple(['table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'instaff_director', 'where' => " state <> '离职' ", 'value' => $info['instaff_director']]),
                    '安装参与人' => selectMultiple(['table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'participants', 'where' => " state <> '离职' ", 'value' => $info['participants']]),
                ],
                [
                    must . '安装时间' => text(['name' => "install_time", 'class' => 'text', 'value' => $info['install_time'], 'laydate' => []]),
                    '安装地点' => text(['name' => "install_address", 'class' => 'text', 'value' => $info['install_address']]),
                ],
                [
                    '安装结果' => textarea(['name' => "install_result", 'class' => 'text', 'value' => $info['install_result']]),
                ],
                [
                    '调试结论' => textarea(['name' => "debug_conclusion", 'class' => 'text', 'value' => $info['debug_conclusion']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'class' => 'installMx',
            'title' => '安装记录',
            'html' => $this->listTable(['tr' => $installTr, 'end' => true]),
        ]);
        $body .= $this->editList([
            'class' => 'debugMx',
            'title' => '调试记录',
            'html' => $this->listTable(['tr' => $debugTr, 'end' => true]),
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, self::title, self::page, self::page . 'EditForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);

        $data['html'] .= <<<EOT
        <style>
            .installMx textarea,.debugMx textarea{
                width: 100%!important;
            }
        </style>
        <script>
            //添加一行
            function addRow(e,type){
                $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                    $(e).closest('tr').after(res.data);
                    resetNumber($(e).closest('tbody'))
                },'json');
            }
            function addEquipment(){
                $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addEquipmentEdit', $("form[name='mxForm']").serialize(),function(resp) {
                 if (resp.warn === 2){
                    $('#installDebugAddEquipment').hide();
                    $("[name='equipment_id']").val(resp.res.id);
                    $("#equipmentName").html(resp.res.name);
                 }else{
                     msg(res.warn);
                 }
                },'json');
            }
        </script>
EOT;

        //返回
        return $this->tab($data);
    }

    /**
     * Desc : 安装记录
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function installRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $type = 'install';
        $id = isset($data[$type.'id'])&&$data[$type.'id']?$data[$type.'id']:self::getId();
        $field = [$type.'operation_item', $type.'purpose', $type.'note', $type.'results'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'installRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'$type')"),
            hidden(['name' => $type . 'id[]', 'value' => $id]) .
            textarea(['name' => $type . 'operation_item[]', 'value' => $array[$type . 'operation_item'], 'title' => '请填写',]),
            textarea(['name' => $type . 'purpose[]', 'value' => $array[$type . 'purpose'], 'title' => '请填写',]),
            textarea(['name' => $type . 'note[]', 'value' => $array[$type . 'note'], 'title' => '请填写',]),
            textarea(['name' => $type . 'results[]', 'value' => $array[$type . 'results'], 'title' => '请填写',]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * Desc : 调试记录
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function debugRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $type = 'debug';
        $id = isset($data[$type.'id'])&&$data[$type.'id']?$data[$type.'id']:self::getId();
        $field = [$type.'rounds', $type.'parameter', $type.'note', $type.'conclusion'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'debugRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'$type')"),
            hidden(['name' => $type . 'id[]', 'value' => $id]) .
            textarea(['name' => $type . 'rounds[]', 'value' => $array[$type . 'rounds'], 'title' => '请填写',]),
            textarea(['name' => $type . 'parameter[]', 'value' => $array[$type . 'parameter'], 'title' => '请填写',]),
            textarea(['name' => $type . 'note[]', 'value' => $array[$type . 'note'], 'title' => '请填写',]),
            textarea(['name' => $type . 'conclusion[]', 'value' => $array[$type . 'conclusion'], 'title' => '请填写',]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        switch ($type) {
            case 'install':
                $res = json_decode($this->installRow(),true);
                $html = $res['html'];
                break;
            case 'debug':
                $res = json_decode($this->debugRow(),true);
                $html = $res['html'];
                break;
            default:
                $html = '';
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    /*基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'client_id' => $this->post('client_id'),
            'equipment_id' => $this->post('equipment_id'),
            'instaff_director' => $this->post('instaff_director'),
            'participants' => $this->post('participants'),
            'install_time' => $this->post('install_time'),
            'install_result' => $this->post('install_result'),
            'debug_conclusion' => $this->post('debug_conclusion'),
            'install_address' => $this->post('install_address'),
        ];
        $annotation = [
            'client_id' => '客户名称',
            'equipment_id' => '设备',
            'instaff_director' => '安装责任人',
            'participants' => '安装参与人',
            'install_time' => '安装时间',
            'install_address' => '安装地点',
        ];
        $rules = [
            'client_id' => 'required',
            'equipment_id' => 'required',
            'instaff_director' => 'required',
            'install_time' => 'required',
        ];

        // 安装记录
        $type = 'install';
        $installIdArr = $this->post($type . 'id')?:[];
        $operation_itemArr = $this->post($type . 'operation_item');
        $purposeArr = $this->post($type . 'purpose');
        $installNoteArr = $this->post($type . 'note');
        $resultsArr = $this->post($type . 'results');
        // 调试记录
        $type = 'debug';
        $idArr = $this->post($type . 'id')?:[];
        $roundsArr = $this->post($type . 'rounds');
        $parameterArr = $this->post($type . 'parameter');
        $noteArr = $this->post($type . 'note');
        $conclusionArr = $this->post($type . 'conclusion');
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif($info['id'] && $info['state'] !='草稿'){
            $json['warn'] = '不是草稿状态，暂不能编辑';
        }else {
            // 开启事务
            $this->startTrans();

            $orderNo = codeTemplateClass::generateCode(self::page,[
                'prefix' => 'WX' . date('Ymd'),
                'table' => self::table,
                'field' => 'orderNo',
                'where' => " and coid = '".self::$coid."' ",
            ],$field);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'state' => '草稿',
                    'orderNo' => $orderNo,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
                $field['orderNo'] = $info['orderNo'];
            }
            if (is_array($idArr)) {
                //安装记录
                foreach ($installIdArr as $k => $nid) {
                    $mx = query(self::tableInstall, "id = '$nid'");
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::tableInstall,
                            'field' => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'operation_item' => $operation_itemArr[$k],
                                'purpose' => $purposeArr[$k],
                                'note' => $installNoteArr[$k],
                                'results' => $resultsArr[$k],
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::tableInstall,
                            'field' => [
                                'operation_item' => $operation_itemArr[$k],
                                'purpose' => $purposeArr[$k],
                                'note' => $installNoteArr[$k],
                                'results' => $resultsArr[$k],
                            ],
                            'where' => "id = '$nid'"
                        ));
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = '编辑安装记录失败';
                        break;
                    }
                }
                delete(['table' => self::tableInstall, 'where' => " id NOT IN ('" . implode("','", $installIdArr) . "') AND orderId = '$id'  "]);
                //调试记录
                foreach ($idArr as $k => $nid) {
                    $mx = query(self::tableDebug, "id = '$nid'");
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::tableDebug,
                            'field' => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'rounds' => $roundsArr[$k],
                                'parameter' => $parameterArr[$k],
                                'note' => $noteArr[$k],
                                'conclusion' => $conclusionArr[$k],
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::tableDebug,
                            'field' => [
                                'rounds' => $roundsArr[$k],
                                'parameter' => $parameterArr[$k],
                                'note' => $noteArr[$k],
                                'conclusion' => $conclusionArr[$k],
                            ],
                            'where' => "id = '$nid'"
                        ));
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = '编辑调试记录失败';
                        break;
                    }
                }
                delete(['table' => self::tableDebug, 'where' => " id NOT IN ('" . implode("','", $idArr) . "') AND orderId = '$id'  "]);
            }

            if (!in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 事务回滚
                $this->rollback();
            } else {
                // 提交事务
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . ($field['orderNo'] ? "，单据编号【{$field['orderNo']}】" : '');
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 详情页
     *
     * @return string
     */
    public function detail(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "提交",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'commit', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=editPage&id=" . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }

            // 安装记录
            $installTr[] = ['作业项', '操作目的', '注意事项', '操作结果'];
            $result = find(['table' => self::tableInstall . " where orderId = '{$info['id']}' order by list"]);
            foreach ((array)$result['array'] as $array) {
                $installTr[] = [$array['operation_item'], $array['purpose'], $array['note'], $array['results']];
            }
            $installTab = $this->listTable(["tr" => $installTr, 'showSort' => true]);
            // 调试记录
            $debugTr[] = ['调试轮次', '关键参数', '注意事项', '调试结论'];
            $result = find(['table' => self::tableDebug . " where orderId = '{$info['id']}' order by list"]);
            foreach ((array)$result['array'] as $array) {
                $debugTr[] = [$array['rounds'], $array['parameter'], $array['note'], $array['conclusion']];
            }
            $debugTab = $this->listTable(["tr" => $debugTr, 'showSort' => true]);
            $kehu = query('kehu', "khid = '$info[client_id]'");
            $equipment = query('equipment', "id = '$info[equipment_id]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                "基本信息" => [
                    [
                        "客户" => $kehu['companyName'],
                        "设备" => $equipment['name'],
                        "安装责任人" => self::findStaff($info['instaff_director']),
                        "安装参与人" => $info['participants']?self::findStaff($info['participants']):'',
                    ],
                    [
                        "安装时间" => self::formatDate($info['install_time']),
                        "安装地点" => $info['install_address'],
                    ],
                    [
                        "安装结果" => pre($info['install_result']),
                    ],
                    [
                        "调试结论" => pre($info['debug_conclusion']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '安装记录',
                'html' => $installTab,
            ]);
            $data['html'] .= $this->detailList([
                'title' => '调试记录',
                'html' => $debugTab,
            ]);
            $data['html'] .= $this->tableShow([
                "系统信息" => [
                    [
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => self::formatDate($info['time']),
                        "更新时间" => self::null($info['updateTime']),
                    ]
                ],
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], self::title)
                    )
                )
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        $append = [];
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此安装调试单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此安装调试单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此安装调试单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm,listForm,contractForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此安装调试单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此安装调试单不是待确认状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "安装调试",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此安装调试单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此安装调试单不是已确认状态，无需撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "安装调试",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】撤回",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此安装调试单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此单据不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "安装调试",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '草稿';

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if ($info[$fieldKey] !== $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】非{$fieldVlaue}状态，无法删除<br>";
                        continue;
                    }
                    // 删除相关 附件
                    $result = self::sqlFind("SELECT id, src FROM `attachFile` WHERE targetId = '{$info['id']}' ");
                    foreach ($result as $key => $attachFile) {
                        delete([
                            'table' => 'attachFile',
                            'where' => " id = '{$attachFile['id']}'",
                        ]);
                        fileDelete($attachFile['src']);
                    }
                    // 删除子表
                    delete([
                        "table" => self::tableInstall,
                        "where" => " orderId = '$id' "
                    ]);
                    delete([
                        "table" => self::tableDebug,
                        "where" => " orderId = '$id' "
                    ]);
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" ."，单据编号【{$info['orderNo']}】". '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条" . self::title;
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     *选择设备
     *
     * @return bool|string
     */
    public function addEquipment(): bool|string
    {
        $html   =
            text(array("name" => "code", "title" => "设备编码")) .
            text(array("name" => "name", "title" => "设备名称"));
        $button = "<input style='margin-left: 5px' onclick=\"addEquipment()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *选择设备
     */
    public function addEquipmentSearch(): bool|string
    {
        $like  = [
            'name' => $this->post('name'),
            'code'   => $this->post('code'),
        ];
        $equal = [
            'coid'   => self::$coid,
            'state'   => '正常',
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page  = $this->page([
            "table"   => "equipment",
            "field"   => "*",
            "where"   => " {$where} ",
            'pageNum' => 50,
            "order"   => "`time` ASC",
        ]);
        //获取表头
        $tr[] = ['', '类别', '设别编码', '设备名称', '规格型号', '出厂编号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
                $array['type'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['factoryNo'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addEquipmentEdit(): bool|string
    {
        $equipmentId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($equipmentId)) {
            $json['warn'] = '请选择设备';
        } else {
            $equipment    = query('equipment', "id = '$equipmentId'");
            $json        = [
                'warn' => 2,
                'res'  => [
                    'name'          => $equipment['name'],
                    'id' => $equipment['id'],

                ],
            ];
        }
        return json_encode($json, 320);
    }
}
